package com.xzh.mallorderapi.api;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.common.util.JsonResult;
import com.xzh.mallorderspi.model.Order;
import com.xzh.mallorderspi.model.search.OrderSeaechBean;
import com.xzh.mallorderspi.model.search.Sales;
import com.xzh.mallorderspi.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "api/orders",produces = MediaType.APPLICATION_JSON_VALUE)
public class OrderApi {
    private OrderService orderService;

    @Autowired
    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }
    @GetMapping
    public ResponseEntity<JsonResult<?>> getOrderById(@RequestParam(defaultValue = "1",value = "pageNo") Integer pageNo,
                                                      @RequestParam(defaultValue = "10",value = "pageSize") Integer pageSize,
                                                      OrderSeaechBean orders){
        Page<Order> page = new Page<>(pageNo, pageSize);
        page = orderService.findAll(orders, page);
        return ResponseEntity.ok(JsonResult.success(page));
    }

    @GetMapping("/id/{id}")
    public ResponseEntity<JsonResult<?>> findById(@PathVariable Integer id){
        System.out.println(id);
        Order order = orderService.findById(id);
        return ResponseEntity.ok(JsonResult.success(order));
    }

    @GetMapping("/order-no/{orderNo}")
    public ResponseEntity<JsonResult<?>> findByOrderNo(@PathVariable String orderNo){
        Order order = orderService.findByOrderNo(orderNo);
        return ResponseEntity.ok(JsonResult.success(order));
    }

    @GetMapping("/seckill-no/{seckillNo}")
    public ResponseEntity<JsonResult<?>> findBySeckillNo(@PathVariable String seckillNo){
        Order order = orderService.findBySeckillNo(seckillNo);
        return ResponseEntity.ok(JsonResult.success(order));
    }

    @GetMapping("/member/{account}")
    public ResponseEntity<JsonResult<?>> findByMember(@PathVariable String account){
        Page<Order> page = new Page<>(1,-1);
        OrderSeaechBean osb = new OrderSeaechBean();
        osb.setMemberAccount(account);
        page.addOrder(OrderItem.desc("created_time"));
        page = orderService.findAll(osb, page);
        return ResponseEntity.ok(JsonResult.success(page));
    }

    @PostMapping
    public ResponseEntity<JsonResult<?>> save(@RequestBody Order order){
        boolean result = orderService.save(order);
        if(result){
            return ResponseEntity.ok(JsonResult.success(result));
        }else {
            return ResponseEntity.ok(JsonResult.fail("订单保存失败"));
        }
    }

    @PutMapping
    public ResponseEntity<JsonResult<?>> update(@RequestBody Order order){
        boolean result = orderService.update(order);
        if(result){
            return ResponseEntity.ok(JsonResult.success(result));
        }else {
            return ResponseEntity.ok(JsonResult.fail("订单更新失败"));
        }
    }

    @PatchMapping("/ship/{orderId}")
    public ResponseEntity<JsonResult<?>> updateForShip(@PathVariable Integer orderId){
        boolean result = orderService.updateForShip(orderId);
        if(result){
            return ResponseEntity.ok(JsonResult.success(result));
        }else {
            return ResponseEntity.ok(JsonResult.fail("订单发货失败"));
        }
    }

    @PatchMapping("/accept/{orderId}")
    public ResponseEntity<JsonResult<?>> updateForAccept(@PathVariable Integer orderId){
        boolean result = orderService.updateForAccept(orderId);
        if(result){
            return ResponseEntity.ok(JsonResult.success(result));
        }else {
            return ResponseEntity.ok(JsonResult.fail("订单收货失败"));
        }
    }

    @DeleteMapping("/{ids}")
    public ResponseEntity<JsonResult<?>> deleteByIds(@PathVariable Integer[] ids,
                                                     @RequestParam(defaultValue = "false") boolean logic){
        int result = orderService.deleteByIds(List.of(ids), logic);
        if(result > 0){
            return ResponseEntity.ok(JsonResult.success(result));
        }else {
            return ResponseEntity.ok(JsonResult.fail("订单删除失败"));
        }
    }




    @GetMapping("/key-metrics")
    public ResponseEntity<Map<String, Object>> getKeyMetrics(@RequestParam("startDate") LocalDate startDate,
                                                             @RequestParam("endDate") LocalDate endDate){
        // 获取原始数据
        Sales sales = orderService.getKeyMetrics(startDate, endDate);

        // 转换为 Map<String, Object> 格式
        Map<String, Object> result = new HashMap<>();
        result.put("totalSales", sales.getTotalSales() != null ? sales.getTotalSales() : BigDecimal.ZERO);
        result.put("totalOrders", sales.getTotalOrders() != null ? sales.getTotalOrders() : BigDecimal.ZERO);
        result.put("totalCustomers", sales.getTotalCustomers() != null ? sales.getTotalCustomers() : BigDecimal.ZERO);
        result.put("avgPrice", sales.getAvgPrice() != null ? sales.getAvgPrice() : BigDecimal.ZERO);

        return ResponseEntity.ok(result);
    }


    @GetMapping("/pay-type")
    public ResponseEntity<?> getPayType(@RequestParam("startDate") LocalDate startDate,
                                        @RequestParam("endDate") LocalDate endDate){
        return ResponseEntity.ok(orderService.getPayType(startDate, endDate));
    }



}



